#include "hc05.h"

void (*onRecvCpl)(char *dat);				// 接收完成回调函数指针
char RecvBuf[100];									// 储存区
uint8_t RecvLen = 0;								// 储存长度

/**
 * HC05初始化
 */
void HC05_Init(void (*callback)(char *dat)){
	onRecvCpl = callback;																		// 设置回调函数
	
	HC05_RCC_APBClkCmd_USART(HC05_CLK,ENABLE);
	HC05_RCC_APBClkCmd_GPIO(HC05_GPIO_CLK,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Pin=HC05_GPIO_PIN_TX;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;							// 复用推挽输出
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(HC05_GPIO_PORT,&GPIO_InitStruct);
	GPIO_InitStruct.GPIO_Pin=HC05_GPIO_PIN_RX;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IN_FLOATING;				// 浮空输入
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(HC05_GPIO_PORT,&GPIO_InitStruct);
	
	USART_DeInit(HC05_PORT);
	USART_InitTypeDef USART_InitStruct;
	USART_InitStruct.USART_BaudRate=9600;
	USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode=USART_Mode_Tx | USART_Mode_Rx;
	USART_InitStruct.USART_Parity=USART_Parity_No;
	USART_InitStruct.USART_StopBits=USART_StopBits_1;
	USART_InitStruct.USART_WordLength=USART_WordLength_8b;
	USART_Init(HC05_PORT,&USART_InitStruct);
	
	USART_ITConfig(HC05_PORT, USART_IT_RXNE,ENABLE);							// 启用接收中断
  USART_ITConfig(HC05_PORT, USART_IT_IDLE,ENABLE);							// 启用空闲中断
    
  NVIC_InitTypeDef NVIC_InitStruct;
  NVIC_InitStruct.NVIC_IRQChannel=HC05_IRQHANDLER_CHANNEL;
  NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0;
  NVIC_InitStruct.NVIC_IRQChannelSubPriority=0;
  NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
  NVIC_Init(&NVIC_InitStruct);

	USART_Cmd(HC05_PORT,ENABLE);
}

/**
 * 已下为四个调试函数
 * 1.发送字节
 * 2.发送字符串
 * 3.发送整数
 * 4.发送浮点数
 */
void HC05_SendByte(char dat){
	while(USART_GetFlagStatus(HC05_PORT,USART_FLAG_TXE)==RESET);
	USART_SendData(HC05_PORT,dat);
}

void HC05_SendString(char *dat){
	while(*dat){
		HC05_SendByte(*dat++);
	}
}

void HC05_SendIntNumber(int num){
	char buf[16];
	sprintf(buf,"%d",num);
	HC05_SendString(buf);
	HC05_SendString("\r\n");
}

void HC05_SendFloatNumber(float num,u8 decimal){
	char buf[16];
	char format_num[12];
	sprintf(format_num,"%%.%df",decimal);
	sprintf(buf,format_num,num);
	HC05_SendString(buf);
	HC05_SendString("\r\n");
}

/**
 * 中断函数
 */
void USART_IRQHANDLER(void){
  if(USART_GetITStatus(HC05_PORT,USART_IT_RXNE) != RESET){				// 接收中断
		char RecvData=USART_ReceiveData(HC05_PORT);
		if(RecvLen < sizeof(RecvBuf)-1){
			RecvBuf[RecvLen++]=RecvData;																// 接收数据
		}
		USART_ClearITPendingBit(HC05_PORT,USART_IT_RXNE);							// 清除标志位
	}else if(USART_GetITStatus(HC05_PORT,USART_IT_IDLE)){						// 空闲中断
		if (RecvLen>0){
			RecvBuf[RecvLen]='\0';
		}
		USART_ReceiveData(HC05_PORT);																	// 正确读取DR寄存器
		USART_ClearITPendingBit(HC05_PORT,USART_IT_IDLE);							// 清除标志位
		RecvLen = 0;
		(*onRecvCpl)(RecvBuf);
	}
}
